package offer;

public class Offer36 {


static class Node {
    public int val;
    public Node left;
    public Node right;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val,Node _left,Node _right) {
        val = _val;
        left = _left;
        right = _right;
    }
}


  static    class Solution {
        Node pre,head;
        public Node treeToDoublyList(Node root) {
            if(root == null) return null;
            dfs(root);
            //todo： 因为是pre是全局变量 所以 dfs完之后 pre指向最后一个节点   而cur已经没有啦
            pre.right =head;
            head.left = pre;
            return head;
        }

        public void dfs(Node cur){
            if(cur==null)
                return;
            dfs(cur.left);
            if(pre!=null) pre.right= cur;
            else head = cur;
            cur.left = pre;
            pre = cur;
            dfs(cur.right);
        }
    }

    public static void main(String[] args) {
        Node node1 = new Node(4);
        Node node2 = new Node(2);
        Node node3 = new Node(5);
        Node node4 = new Node(1);
        Node node5 = new Node(3);
        node1.left=node2;
        node1.right=node3;
        node2.left=node4;
        node2.right=node5;

        Solution solution = new Solution();
        Node node = solution.treeToDoublyList(node1);

    }





}
